package com.hs.carrental.task;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hs.carrental.entity.Order;
import com.hs.carrental.mapper.CarMapper;
import com.hs.carrental.mapper.OrderMapper;
import com.hs.carrental.service.ICarService;
import com.hs.carrental.service.IOrderService;
import com.hs.carrental.util.Helper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Component
@Slf4j
@EnableScheduling
public class RentalTask {

    @Resource
    private IOrderService orderService;

    @Resource
    private OrderMapper orderMapper;

    @Resource
    private ICarService carService;

    @Resource
    private CarMapper carMapper;

    /**
     * 每30s执行一次 到租车开始时间未取车的订单 状态更新为0
     */
    @Scheduled(cron = "0/30 * * * * ?")
    @Transactional(rollbackFor = Exception.class)
    public void dealOrders(){
        List<Integer> carIds = new ArrayList<>();
        LocalDateTime now = LocalDateTime.now();
        QueryWrapper<Order> queryWrapper = new QueryWrapper<>();
        queryWrapper.le("rentTime",now).eq("orderState",1);
        List<Order> orders = orderMapper.selectList(queryWrapper);
        if (!Helper.isEmpty(orders)){
            carIds = orders.stream().map(Order::getCarId).collect(Collectors.toList());
            orders.forEach(order -> {
                order.setOrderState(0);
            });
            //订单状态更新为0
            orderService.updateBatchById(orders);
        }
        if (!Helper.isEmpty(carIds)){
            //车辆状态更新为0
            carMapper.updateTo0(carIds);
        }
    }
}
